package com.qk.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;

/**
 * 第一步：引入工具类
 * 将官方Demo文档，改为一个工具类，方便案例中调用
 */
@Slf4j
@Component  // Spring的IOC容器，声明bean的基础注解（当不属于三层架构类时用此注解）
public class AliyunOSSOperator {

//    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
//    private static final String BUCKET_NAME = "du-sir-ai-web";
//    private static final String REGION = "cn-beijing";

    /**
     * 通过@Value注解动态注入配置值
     * 把这些需要灵活变动的参数，统一配置在.yml配置文件中，这样以后改动时，就不需要一个个java文件中去找了，提高效率
     */
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.region}")
    private String region;

    public String upload(byte[] content, String objectName) throws Exception {
        // 创建OSSClient实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));
            // 上传文件
            ossClient.putObject(putObjectRequest);
            /* 返回文件访问URL
                    像这种效果【https://du-sir-ai-web.oss-cn-beijing.aliyuncs.com/001.jpg】*/
            return "https://" + bucketName + "." + endpoint.substring(8) + "/" + objectName;
        } catch (Exception e) {
            log.error("Caught an OSSException: " + e.getMessage());
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}